<template>
  <div class="outfits">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>搭配管理</h2>
        <p>创建和管理你的搭配方案，记录每一次精彩穿搭</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="$router.push('/outfits/create')">
          <el-icon><Plus /></el-icon>
          创建搭配
        </el-button>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索搭配名称..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterStyle" placeholder="选择风格" clearable @change="handleFilter">
            <el-option label="全部风格" value="" />
            <el-option label="休闲" value="casual" />
            <el-option label="正式" value="formal" />
            <el-option label="商务" value="business" />
            <el-option label="运动" value="sport" />
            <el-option label="派对" value="party" />
            <el-option label="复古" value="vintage" />
            <el-option label="街头" value="street" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterSeason" placeholder="选择季节" clearable @change="handleFilter">
            <el-option label="全部季节" value="" />
            <el-option label="春季" value="spring" />
            <el-option label="夏季" value="summer" />
            <el-option label="秋季" value="autumn" />
            <el-option label="冬季" value="winter" />
            <el-option label="四季" value="all" />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort">
            <el-option label="创建时间" value="created_at" />
            <el-option label="最后穿着" value="last_worn" />
            <el-option label="穿着次数" value="wear_count" />
            <el-option label="评分" value="rating" />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-select v-model="minRating" placeholder="最低评分" clearable @change="handleFilter">
            <el-option label="1星以上" :value="1" />
            <el-option label="2星以上" :value="2" />
            <el-option label="3星以上" :value="3" />
            <el-option label="4星以上" :value="4" />
            <el-option label="5星" :value="5" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <div class="view-controls">
            <el-switch
              v-model="showFavoriteOnly"
              active-text="仅收藏"
              @change="handleFilter"
            />
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 搭配列表 -->
    <div class="outfits-grid" v-loading="loading">
      <div
        v-for="outfit in outfitList"
        :key="outfit.id"
        class="outfit-card"
        @click="viewOutfitDetail(outfit.id)"
      >
        <div class="card-image">
          <el-image
            :src="outfit.main_image || '/placeholder.jpg'"
            fit="cover"
            class="outfit-image"
          />
          <div class="card-overlay">
            <el-button-group>
              <el-button size="small" @click.stop="editOutfit(outfit)">
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button size="small" @click.stop="copyOutfit(outfit)">
                <el-icon><CopyDocument /></el-icon>
              </el-button>
              <el-button size="small" @click.stop="toggleFavorite(outfit)">
                <el-icon><Star v-if="!outfit.is_favorite" /><StarFilled v-else /></el-icon>
              </el-button>
              <el-button size="small" type="danger" @click.stop="deleteOutfit(outfit)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </el-button-group>
          </div>
          <div class="favorite-badge" v-if="outfit.is_favorite">
            <el-icon><StarFilled /></el-icon>
          </div>
          <div class="today-badge" v-if="outfit.isWearingToday">
            <span>今日穿搭</span>
          </div>

        </div>

        <div class="card-content">
          <div class="outfit-name">{{ outfit.name }}</div>
          <div class="outfit-meta">
            <span class="style">{{ getStyleText(outfit.style) }}</span>
            <span class="season">{{ getSeasonText(outfit.season) }}</span>
          </div>

          <div class="outfit-stats">
            <div class="stat-item">
              <el-icon><View /></el-icon>
              <span>{{ outfit.wear_count }}次</span>
            </div>
            <div class="stat-item" v-if="outfit.rating">
              <el-rate
                v-model="outfit.rating"
                disabled
                size="small"
                show-score
                text-color="#ff9900"
              />
            </div>
          </div>

          <div class="clothing-preview">
            <div class="preview-label">包含衣服：</div>
            <div class="clothing-items">
              <el-image
                v-for="(item, index) in outfit.clothes.slice(0, 4)"
                :key="index"
                :src="item.main_image || '/placeholder.jpg'"
                fit="cover"
                class="clothing-thumb"
              />
              <div v-if="outfit.clothes.length > 4" class="more-count">
                +{{ outfit.clothes.length - 4 }}
              </div>
            </div>
          </div>

          <div class="outfit-actions">
            <el-button size="small" type="primary" @click.stop="wearOutfit(outfit)">
              <el-icon><Check /></el-icon>
              今天穿这套
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[12, 24, 48]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { outfitAPI } from '@/api'
import { createListLoader } from '@/utils/api-helper'

// 路由实例
const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const filterStyle = ref('')
const filterSeason = ref('')
const sortBy = ref('created_at')
const minRating = ref('')
const showFavoriteOnly = ref(false)
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const outfitList = ref([])
const loading = ref(false)

// 模拟数据作为后备
const fallbackData = [
  {
    id: 1,
    name: '商务休闲',
    style: 'business',
    season: 'all',
    wear_count: 5,
    rating: 4.5,
    is_favorite: true,
    main_image: '',
    clothes: [
      { id: 1, main_image: '' },
      { id: 2, main_image: '' },
      { id: 3, main_image: '' }
    ],
    created_at: '2024-01-15'
  },
  {
    id: 2,
    name: '周末出游',
    style: 'casual',
    season: 'spring',
    wear_count: 3,
    rating: 4.0,
    is_favorite: false,
    main_image: '',
    clothes: [
      { id: 4, main_image: '' },
      { id: 5, main_image: '' },
      { id: 6, main_image: '' },
      { id: 7, main_image: '' }
    ],
    created_at: '2024-01-10'
  }
]

// 创建加载函数
const loadOutfitList = createListLoader(
  outfitAPI.getList,
  { loading, list: outfitList, total },
  () => {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value || undefined,
      style: filterStyle.value || undefined,
      season: filterSeason.value || undefined,
      sortBy: sortBy.value,
      minRating: minRating.value || undefined,
    }

    // 如果只显示收藏的
    if (showFavoriteOnly.value) {
      params.is_favorite = 'true'
    }

    return params
  },
  { fallbackData }
)

// 方法
const handleSearch = () => {
  currentPage.value = 1
  loadOutfitList()
}

const handleFilter = () => {
  currentPage.value = 1
  loadOutfitList()
}

const handleSort = () => {
  loadOutfitList()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  loadOutfitList()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadOutfitList()
}

const viewOutfitDetail = (id) => {
  // 跳转到详情页
  router.push(`/outfits/${id}`)
}

const editOutfit = (outfit) => {
  // 跳转到编辑页面
  router.push(`/outfits/${outfit.id}/edit`)
}

const copyOutfit = async (outfit) => {
  try {
    await outfitAPI.copy(outfit.id)
    ElMessage.success('搭配已复制')
    loadOutfitList() // 重新加载列表
  } catch (error) {
    console.error('复制搭配失败:', error)
    ElMessage.error('复制失败，请稍后重试')
  }
}

const toggleFavorite = async (outfit) => {
  try {
    await outfitAPI.toggleFavorite(outfit.id)
    outfit.is_favorite = !outfit.is_favorite
    ElMessage.success(outfit.is_favorite ? '已收藏' : '已取消收藏')
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

const deleteOutfit = (outfit) => {
  ElMessageBox.confirm('确定要删除这套搭配吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await outfitAPI.delete(outfit.id)
      ElMessage.success('删除成功')
      loadOutfitList() // 重新加载列表
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

const wearOutfit = async (outfit) => {
  try {
    // 使用专门的"今天穿这套"API
    const response = await outfitAPI.wearToday(outfit.id)



    if (response.data.alreadySelected) {
      ElMessage.info('今天已经选择了这套搭配')
    } else if (response.data.replaced) {
      ElMessage.success(response.message || '已更换今日穿搭')

      // 立即更新本地数据
      outfitList.value.forEach(item => {
        if (item.id === outfit.id) {
          item.isWearingToday = true
          item.wear_count = response.data.newWearCount
          item.last_worn_date = new Date().toISOString().split('T')[0]
        } else {
          item.isWearingToday = false // 清除其他搭配的今日标识
        }
      })
    } else {
      ElMessage.success(response.message || '已记录今日穿搭')

      // 立即更新本地数据
      outfitList.value.forEach(item => {
        if (item.id === outfit.id) {
          item.isWearingToday = true
          item.wear_count = response.data.newWearCount
          item.last_worn_date = new Date().toISOString().split('T')[0]
        } else {
          item.isWearingToday = false // 清除其他搭配的今日标识
        }
      })
    }

    // 重新加载列表以确保数据完全同步
    setTimeout(() => {
      loadOutfitList()
    }, 100)
  } catch (error) {
    console.error('记录穿搭失败:', error)
    ElMessage.error('记录穿搭失败，请稍后重试')
  }
}

// 辅助方法
const getStyleText = (style) => {
  const styles = {
    casual: '休闲',
    formal: '正式',
    business: '商务',
    sport: '运动',
    party: '派对',
    vintage: '复古',
    street: '街头'
  }
  return styles[style] || '未知'
}

const getSeasonText = (season) => {
  const seasons = {
    spring: '春季',
    summer: '夏季',
    autumn: '秋季',
    winter: '冬季',
    all: '四季'
  }
  return seasons[season] || '未知'
}

onMounted(() => {
  loadOutfitList()
})
</script>

<style scoped>
.outfits {
  width: 100%;
  height: 100%;
  padding: 0;
  overflow-y: auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left h2 {
  margin: 0 0 5px 0;
  color: #303133;
}

.header-left p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
}

.view-controls {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.outfits-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
  width: 100%;
}

.outfit-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
  flex: 0 0 calc(25% - 15px);
  min-width: 280px;
  max-width: 400px;
}

.outfit-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.card-image {
  position: relative;
  height: 200px;
}

.outfit-image {
  width: 100%;
  height: 100%;
}

.card-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.outfit-card:hover .card-overlay {
  opacity: 1;
}

.favorite-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  color: #f56c6c;
  font-size: 20px;
}

.today-badge {
  position: absolute;
  top: 8px;
  left: 8px;
  background: linear-gradient(45deg, #409eff, #67c23a);
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 10px;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  z-index: 10;
  white-space: nowrap;
}

.card-content {
  padding: 15px;
}

.outfit-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
}

.outfit-meta {
  display: flex;
  gap: 10px;
  font-size: 12px;
  color: #909399;
  margin-bottom: 10px;
}

.outfit-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
  color: #606266;
}

.clothing-preview {
  margin-bottom: 15px;
}

.preview-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.clothing-items {
  display: flex;
  gap: 5px;
  align-items: center;
}

.clothing-thumb {
  width: 30px;
  height: 30px;
  border-radius: 4px;
}

.more-count {
  font-size: 12px;
  color: #909399;
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 10px;
}

.outfit-actions {
  text-align: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .outfit-card {
    flex: 0 0 calc(33.333% - 14px);
  }
}

@media (max-width: 1000px) {
  .outfit-card {
    flex: 0 0 calc(50% - 10px);
  }
}

@media (max-width: 600px) {
  .outfit-card {
    flex: 0 0 100%;
    max-width: none;
  }

  .outfits-grid {
    gap: 15px;
  }
}
</style>
